import torch
import torch.nn as nn
import torchvision.models as models
import math

def conv3x3(in_planes, out_planes, stride=1):
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)


class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class ResNet18(nn.Module):
    def __init__(self):
        super(ResNet18, self).__init__()
        self.inplanes = 64
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        self.layer1 = self._make_layer(BasicBlock, 64, 2)
        self.layer2 = self._make_layer(BasicBlock, 128, 2, stride=2)
        self.layer3_sm = self._make_layer(BasicBlock, 256, 2, stride=2)
        self.layer4_sm = self._make_layer(BasicBlock, 512, 2, stride=2)

        self.inplanes = 128
        self.layer3_im = self._make_layer(BasicBlock, 256, 2, stride=2)
        self.layer4_im = self._make_layer(BasicBlock, 512, 2, stride=2)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, 0.01)
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            
    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)


    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x0 = self.maxpool(x)

        x1 = self.layer1(x0)
        x2 = self.layer2(x1)
        x3 = self.layer3_sm(x2)
        x4 = self.layer4_sm(x3)

        return {"X0": x0, "X1": x1, "X2": x2, "X3": x3, "X4": x4}
    
def init_weight(resnent18):
    pretrained = models.resnet18()
    pretrained.load_state_dict(torch.load("./resnet18.pth"))
    pretrained_dict = pretrained.state_dict()

    all_params = {}
    count = 0
    for k, v in resnent18.state_dict().items():
        if k in pretrained_dict.keys():
            count+=1
            v = pretrained_dict[k]
            all_params[k] = v
        elif '_sm' in k:
            count+=1
            name = k.split('_sm')[0] + k.split('_sm')[1]
            v = pretrained_dict[name]
            all_params[k] = v
        elif '_im' in k:
            name = k.split('_im')[0] + k.split('_im')[1]
            v = pretrained_dict[name]
            all_params[k] = v
    assert len(all_params.keys()) == len(resnent18.state_dict().keys())
    resnent18.load_state_dict(all_params)

if __name__ == "__main__":
    a = ResNet18()
    init_weight(a)